#include <bits/stdc++.h>
using namespace std;
#define int long long
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
char ch[2]={'A','B'};
struct node 
{
    int x,y,c,k;
};
struct z 
{
    int x,y,z;
};
const int N=1e3+5;
void solve()
{
    int n,m,k;
    cin>>n>>m>>k;
    vector<vector<char>>v(n+1,vector<char>(m+1));
    //vector<vector<z>>f(n+1,vector<z>(m+1));
    //bool f[n][m][13]={0};
    vector<vector<vector<bool>>> f(n+1,vector<vector<bool>>(m+1,vector<bool>(12)));
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            cin>>v[i][j];
        }
    }
    queue<node> q;
    f[1][1][1%k]=1;
    q.push({1,1,0,1});
    while(q.size())
    {
        auto tmp=q.front();
        q.pop();
        int x=tmp.x,y=tmp.y,c=tmp.c,tk=tmp.k;
        if(x==n&&y==m)
        {
            cout<<c<<endl;
            return ;
        }
        for(int i=0;i<4;i++)
        {
            int xx=x+dx[i],yy=y+dy[i];
            if(xx<1||xx>n||yy<1||y>m||v[xx][yy]!=ch[tk/k%2]||f[xx][yy][(tk+1)%k])continue;
            f[xx][yy][(tk+1)%k]=true;
            q.push({xx,yy,c+1,tk+1});
            //q.push({xx,yy,c+1,tk+(k-(tk%k))/2});
            //cout<<xx<<" "<<yy<<" "<<tk<<endl;
        }
    }
    cout<<-1<<endl;
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T=1;
    //cin>>T;
    while(T--)
    {
       solve();
    }
    return 0;
}